#! /usr/bin/python3

import logging
import os
from Utils.TimeUtil import *


class MyLogger:

    def __init__(self, path, clevel=logging.INFO, flevel=logging.INFO, showTime=True, isByDay=True, isPin=False):
        if isByDay:
            path = path.replace(".log", "_" + getFormatTimeToday() + ".log")
        if isPin:
            path = path.replace(".log", "_Pin" + stampS2TimeStr(getStamp10(), fmt="HM") + ".log")
        self.logPath = path
        self.logger = logging.getLogger(path)
        self.logger.setLevel(logging.DEBUG)
        dir, fileName = os.path.split(path)
        if not os.path.exists(dir):
            pass #2204# print(dir, " not exists, create it now!")
            os.makedirs(dir)
            foo = open(path, "w")
            foo.close()
        if showTime:
            fmt = logging.Formatter(
                '[%(asctime)s.%(msecs)03d] [%(levelname)s] %(message)s',
                '%Y-%m-%d %H:%M:%S')
        else:
            fmt = logging.Formatter('%(message)s')

        # 设置CMD日志
        if clevel != -404:
            sh = logging.StreamHandler()
            sh.setFormatter(fmt)
            sh.setLevel(clevel)
            self.logger.addHandler(sh)

        # 设置文件日志
        if flevel != -404:
            fh = logging.FileHandler(path, encoding="utf-8", mode="a")
            fh.setFormatter(fmt)
            fh.setLevel(flevel)
            self.logger.addHandler(fh)
    # def getCommonLogger(self):
    #     return MyLogger(r"./Logs/%s.log" % ('all'), logging.DEBUG, logging.DEBUG)
    def setLogPath(self, logPath):
        self.logPath = logPath
        self.logger = logging.getLogger(logPath)

    def getLogPath(self):
        return self.logPath

    def debug(self, message, *msgs):
        if len(msgs) > 0:
            message = str(message) + '\t' + '\t'.join([str(ee) for ee in msgs])
        self.logger.debug(message)

    def info(self, message, *msgs):
        if len(msgs) > 0:
            message = str(message) + '\t' + '\t'.join([str(ee) for ee in msgs])
        self.logger.info(message)

    def warn(self, message, *msgs):
        if len(msgs) > 0:
            message = str(message) + '\t' + '\t'.join([str(ee) for ee in msgs])
        self.logger.warning(message)

    def error(self, message, *msgs):
        if len(msgs) > 0:
            message = str(message) + '\t' + '\t'.join([str(ee) for ee in msgs])
        self.logger.error(message)

    def cri(self, message, *msgs):
        if len(msgs) > 0:
            message = str(message) + '\t' + '\t'.join([str(ee) for ee in msgs])
        self.logger.critical(message)


if __name__ == '__main__':
    logyyx = MyLogger(r'Logs/test.log', logging.ERROR, logging.ERROR)
    logyyx.debug('一个debug信息')
    logyyx.info('一个info信息')
    logyyx.warn('一个warning信息')
    logyyx.error('一个error信息')
    logyyx.cri('一个致命critical信息')
